package com.hejing.线程安全问题;

/**
 * ClassName: WindowTest01
 * Package: com.hejing.线程安全问题
 * Description:
 *      使用继承Thread的方式，实现卖票
 * @Author: HeJing
 * @Create: 2023-04-14 19:31
 * @Version: 1.0
 */
public class WindowWithSynchronizedFuncTest01 {
    public static void main(String[] args) {
        SaleTicket01WithSynFunc s1 = new SaleTicket01WithSynFunc();
        SaleTicket01WithSynFunc s2 = new SaleTicket01WithSynFunc();
        SaleTicket01WithSynFunc s3 = new SaleTicket01WithSynFunc();

        s1.setName("窗口1");
        s2.setName("窗口2");
        s3.setName("窗口3");

        s1.start();
        s2.start();
        s3.start();
    }
}

class SaleTicket01WithSynFunc extends Thread {

    static int ticket = 100;
    static boolean isFlag = true;

//    public synchronized void synFuncTest01() {  // 这种形式使用默认同步构造器: this, 此时的this指向的对象不再唯一，线程不安全。
//        if (ticket > 0) {
//            System.out.println(Thread.currentThread().getName() + "售票，票号: " + (101 - ticket));
//            ticket--;
//        } else {
//            isFlag = false;
//        }
//    }

    public static void synFuncTest02() {  // 对于静态方法，此时同步方法的默认同步监视器是 "当前类.class"
        if (ticket > 0) {
            System.out.println(Thread.currentThread().getName() + "售票，票号: " + (101 - ticket));
            ticket--;
        } else {
            isFlag = false;
        }
    }


    public void synFuncTest01() {
        synchronized (SaleTicket01WithSynFunc.class) {
            if (ticket > 0) {
                System.out.println(Thread.currentThread().getName() + "售票，票号: " + (101 - ticket));
                ticket--;
            } else {
                isFlag = false;
            }
        }
    }


    @Override
    public void run() {
        while(isFlag) {
            try{
                Thread.sleep(10);
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            synFuncTest01();
        }
    }
}




















